package com.xxx.store.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxx.store.entity.User;
import com.xxx.store.service.UserService;
import com.xxx.store.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-04-02
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController<User, UserService>{

    @Autowired
    UserService userService;


    @PostMapping("/login")
    public Result login(@RequestBody User form){
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", form.getUsername());
        qw.eq("password", form.getPassword());
        User db = userService.getOne(qw);
        System.out.println(db);
        if(db == null){
            return Result.error("用户名或者密码错误");
        }else{
            String roles = db.getRoles(); // "2,3" //管理员 2   用户 1
            //是否包含此角色
            int i = roles.indexOf(form.getRoles()); // "2"   “1”
            //控制管理员登陆前段页面
            if(i != -1){
                return Result.ok("登录成功", db);
            }else{
                return Result.error("该角色没有页面权限");
            }
        }
    }

    @GetMapping("/getUserById")
    public Result getUserById(Integer id){
        User user = userService.getById(id);
        return Result.ok(user);
    }

    @GetMapping("/del")
    public Result del(Integer id){
       userService.removeById(id);
        return Result.ok("删除成功");
    }

    @PostMapping("/update")
    public Result update(@RequestBody User user){
        userService.updateById(user);
        return Result.ok("更新成功", user);
    }

    @PostMapping("/add")
    public Result add(@RequestBody User user){
        Date date = new Date();
        int count = userService.count(new QueryWrapper<User>().eq("username", user.getUsername()));
        if(count == 0){
            user.setCreateTime(date);
            userService.save(user);
            return Result.ok("添加成功");
        }else{
            return Result.error("用户名已经存在");
        }
    }

    @GetMapping("/getListByRoles")
    public Result getListByRoles(String roles){
        List<User> userList = userService.list(
                new QueryWrapper<User>().eq("roles", roles)
        );
        return Result.ok(userList);
    }

    @GetMapping("/list")
    public Result list(){
        List<User> userList = userService.list();
        return Result.ok(userList);
    }



}

